import React, { useEffect, useState, FC, ReactNode, memo, useMemo } from 'react'
import { NavBar, Tabs } from 'antd-mobile'
import dayjs from 'dayjs'
import qs from 'qs'
import { getOrderListApi } from './api'
import ic_server from '@/assets/images/ic_server.png'
import MyOrderWrapper from './style'
import { useLocation, useNavigate } from 'react-router-dom'

interface Iprops {
  children?: ReactNode
}
const Order: FC<Iprops> = () => {
  const { search } = useLocation()
  const obj = useMemo(() => qs.parse(search.slice(1)), [search])
  const [activeKey, setActiveKey] = useState<string>(
    (obj.state as string) || ''
  )
  const [orderList, setOrderList] = useState<any[]>([])

  // if (obj.state !== activeKey) {
  //   setActiveKey(obj.state as string)
  // }

  // 获取订单列表
  const handleGetOrderList = async () => {
    const result = await getOrderListApi(activeKey)
    const newList = result.data.map((item: any) => {
      const expireTime =
        new Date(item.order_start_time).getTime() + 2 * 60 * 60 * 1000
      const countdown = expireTime - Date.now()
      return { ...item, countdown }
    })
    setOrderList(newList)
  }

  // 倒计时 + 自动刷新逻辑
  useEffect(() => {
    if (!orderList.length) return

    const timer = setInterval(() => {
      let needRefresh = false

      setOrderList((prev) =>
        prev.map((item) => {
          if (item.trade_state !== '待支付') return item
          const newCountdown = item.countdown - 1000
          if (newCountdown <= 0) {
            needRefresh = true
            return { ...item, countdown: 0 }
          }
          return { ...item, countdown: newCountdown }
        })
      )

      if (needRefresh) {
        handleGetOrderList()
      }
    }, 1000)

    return () => clearInterval(timer)
  }, [orderList])

  // tab切换时重新请求
  useEffect(() => {
    handleGetOrderList()
  }, [activeKey])

  const formatTime = (ms: number) => {
    if (ms <= 0) return '已超时'
    const totalSec = Math.floor(ms / 1000)
    const h = String(Math.floor(totalSec / 3600)).padStart(2, '0')
    const m = String(Math.floor((totalSec % 3600) / 60)).padStart(2, '0')
    const s = String(totalSec % 60).padStart(2, '0')
    return `${h}:${m}:${s}`
  }

  const tabs = [
    { key: '', title: '全部' },
    { key: '1', title: '待支付' },
    { key: '2', title: '待服务' },
    { key: '3', title: '已完成' },
    { key: '4', title: '已取消' }
  ]
  const navigate = useNavigate()
  const handleGoDetail = (item: any) => {
    console.log(item.out_trade_no)
    navigate(`/detail?oid=${item.out_trade_no}`)
  }

  return (
    <MyOrderWrapper>
      <NavBar backArrow={false}>我的订单</NavBar>

      <Tabs activeKey={activeKey} onChange={setActiveKey}>
        {tabs.map((tab) => (
          <Tabs.Tab title={tab.title} key={tab.key}></Tabs.Tab>
        ))}
      </Tabs>

      <div className="order-list">
        {orderList.map((item, index) => (
          <div
            className="order-card"
            key={index}
            onClick={() => handleGoDetail(item)}
          >
            <img src={ic_server} className="order-img" alt="服务" />
            <div className="order-info">
              <div className="order-title">就医陪诊（尊享）</div>
              <div className="order-time">
                预约时间：
                {dayjs(item.order_start_time).format('YYYY-MM-DD HH:mm')}
              </div>
              <div className="order-hospital">{item.hospital_name}</div>
            </div>

            {item.trade_state === '待支付' ? (
              <div
                className={`order-status ${
                  item.countdown <= 0 ? 'status-expired' : 'status-wait'
                }`}
              >
                {item.countdown <= 0
                  ? '已超时'
                  : `待支付
                  （${formatTime(item.countdown)}）
                  `}
              </div>
            ) : (
              <div
                className="order-status status-done"
                style={{
                  color: item.trade_state === '已取消' ? '#999' : '#00c853'
                }}
              >
                {item.trade_state}
              </div>
            )}
          </div>
        ))}
        <div className="no-more">没有更多了</div>
      </div>
    </MyOrderWrapper>
  )
}

export default memo(Order)
